package com.woniuxy.woniuticket.notification.listener;

import com.woniuxy.woniuticket.notification.util.TestTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.Calendar;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
@Component
@Slf4j
public class TimerListener implements ServletContextListener{


    private Timer timer = null;

    private AmqpTemplate amqpTemplate;
    @Override
    public void contextInitialized(ServletContextEvent event) {
        timer = new Timer(true);
//        event.getServletContext().log("定时器已启动");
        amqpTemplate = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean(AmqpTemplate.class);
        //设置执行时间
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
        //定制每天的11:00:00执行
        calendar.set(year, month, day, 14, 33, 30);
        java.util.Date date = calendar.getTime();
        int period = 30 * 1000000;
        //每天的date时刻执行TestTask，每隔30秒重复执行
        timer.schedule(new TestTask(amqpTemplate), date, period);
//        每天的date时刻执行TestTask, 仅执行一次
//        timer.schedule(new TestTask(amqpTemplate), date);
    }


    @Override
    public void contextDestroyed(ServletContextEvent event) {
        if (timer != null) {
            timer.cancel();
            //event.getServletContext().log("定时器销毁");

        }
    }
}